package com.smart.mac.interceptor;

import com.smart.mac.common.CommonConstants;
import com.smart.mac.model.vo.UserDemoVO;
import com.smart.mac.utls.CacheManagerUtils;
import com.smart.mac.utls.LocalSessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * LoginInterceptor
 *
 * @Description
 * @Author mac
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isEmpty(header) || !header.startsWith(CommonConstants.BEARER)){
            throw new RuntimeException("请求头token不能为空");
        }
        String token = header.substring(7);
        log.info("用户token:{}",token);
        UserDemoVO demoVO = CacheManagerUtils.get(token);
        if (demoVO == null){
            throw new RuntimeException("用户不存在");
        }
        LocalSessionUtils.put(demoVO);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LocalSessionUtils.remove();
    }
}
